import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
// NOTE: modules/editor has been removed. If theme registration is needed in future,
// reintroduce minimal monaco theme utils locally or use Workspace editor utilities.
// Temporarily comment out imports to avoid build errors.
// import { registerCustomTheme } from '../modules/editor/utils/monaco';
// import type { ThemeConfig } from '../modules/editor/types/editor';

export interface EditorActionDefinition {
  id: string;
  label: string;
  keybindings?: number[]; // monaco KeyCode/KeyMod 组合
  precondition?: string;
  contextMenuGroupId?: string;
  contextMenuOrder?: number;
  run: (editor: monaco.editor.IStandaloneCodeEditor) => void | Promise<void>;
}

const editorInstances = new Set<monaco.editor.IStandaloneCodeEditor>();
const globalEditorActions: Map<string, EditorActionDefinition> = new Map();

export function registerEditorInstance(editor: monaco.editor.IStandaloneCodeEditor) {
  editorInstances.add(editor);
  // 将所有全局 action 应用到新创建的编辑器
  for (const action of globalEditorActions.values()) {
    // 避免重复注册
    const exists = editor.getAction(action.id);
    if (!exists) {
      editor.addAction({
        id: action.id,
        label: action.label,
        keybindings: action.keybindings,
        precondition: action.precondition,
        contextMenuGroupId: action.contextMenuGroupId,
        contextMenuOrder: action.contextMenuOrder,
        run: () => action.run(editor),
      });
    }
  }
}

export function unregisterEditorInstance(editor: monaco.editor.IStandaloneCodeEditor) {
  editorInstances.delete(editor);
  // 说明：Monaco 没有移除 addAction 的 API，这里仅移除实例引用，避免内存泄漏
}

export function registerAction(def: EditorActionDefinition): { dispose(): void } {
  if (!globalEditorActions.has(def.id)) {
    globalEditorActions.set(def.id, def);
    // 将 action 推送到所有现存编辑器
    for (const ed of editorInstances) {
      const exists = ed.getAction(def.id);
      if (!exists) {
        ed.addAction({
          id: def.id,
          label: def.label,
          keybindings: def.keybindings,
          precondition: def.precondition,
          contextMenuGroupId: def.contextMenuGroupId,
          contextMenuOrder: def.contextMenuOrder,
          run: () => def.run(ed),
        });
      }
    }
  } else {
    console.warn(`[editorExtensionService] Action '${def.id}' already exists, skip duplicate.`);
  }

  return {
    dispose() {
      // 说明：Monaco 未提供移除 action 的 API，此处仅从全局注册表删除，
      // 不会再应用到之后创建的编辑器实例；已存在实例上的 action 将保留。
      globalEditorActions.delete(def.id);
    },
  };
}

// 语言提供者封装（都返回 monaco 的 IDisposable，可在插件 deactivate 时统一 dispose）
export function registerCompletionProvider(languageId: string, provider: monaco.languages.CompletionItemProvider): monaco.IDisposable {
  return monaco.languages.registerCompletionItemProvider(languageId, provider);
}

// 新增：内联补全提供者注册
export function registerInlineCompletionsProvider(languageId: string, provider: monaco.languages.InlineCompletionsProvider): monaco.IDisposable {
  return monaco.languages.registerInlineCompletionsProvider(languageId, provider);
}

export function registerHoverProvider(languageId: string, provider: monaco.languages.HoverProvider): monaco.IDisposable {
  return monaco.languages.registerHoverProvider(languageId, provider);
}

export function registerCodeActionProvider(languageId: string, provider: monaco.languages.CodeActionProvider): monaco.IDisposable {
  return monaco.languages.registerCodeActionProvider(languageId, provider);
}

export function registerDocumentFormattingEditProvider(languageId: string, provider: monaco.languages.DocumentFormattingEditProvider): monaco.IDisposable {
  return monaco.languages.registerDocumentFormattingEditProvider(languageId, provider);
}

export function registerDocumentRangeFormattingEditProvider(languageId: string, provider: monaco.languages.DocumentRangeFormattingEditProvider): monaco.IDisposable {
  return monaco.languages.registerDocumentRangeFormattingEditProvider(languageId, provider);
}

export function registerDefinitionProvider(languageId: string, provider: monaco.languages.DefinitionProvider): monaco.IDisposable {
  return monaco.languages.registerDefinitionProvider(languageId, provider);
}

export function registerReferenceProvider(languageId: string, provider: monaco.languages.ReferenceProvider): monaco.IDisposable {
  return monaco.languages.registerReferenceProvider(languageId, provider);
}

export function registerRenameProvider(languageId: string, provider: monaco.languages.RenameProvider): monaco.IDisposable {
  return monaco.languages.registerRenameProvider(languageId, provider);
}

// 主题与语言注册（本地实现替代被移除的 modules/editor 工具）
export interface ThemeConfig {
  id: string;
  themeData?: monaco.editor.IStandaloneThemeData;
  base?: 'vs' | 'vs-dark' | 'hc-black' | 'hc-light';
  inherit?: boolean;
  rules?: any[];
  colors?: Record<string, string>;
}

export function registerTheme(theme: ThemeConfig | any): void {
  if (!theme) return;
  const id = theme.id || theme.name || 'custom-theme';
  const data: monaco.editor.IStandaloneThemeData = theme.themeData ?? {
    base: (theme.base as monaco.editor.BuiltinTheme) ?? 'vs',
    inherit: theme.inherit ?? true,
    rules: theme.rules ?? [],
    colors: theme.colors ?? {},
  };
  monaco.editor.defineTheme(id, data);
}

export function setTheme(themeId: string): void {
  monaco.editor.setTheme(themeId);
}

export function registerLanguage(config: {
  id: string;
  monarchTokensProvider?: any;
  languageConfiguration?: monaco.languages.LanguageConfiguration;
}): void {
  monaco.languages.register({ id: config.id });
  if (config.monarchTokensProvider) {
    monaco.languages.setMonarchTokensProvider(config.id, config.monarchTokensProvider);
  }
  if (config.languageConfiguration) {
    monaco.languages.setLanguageConfiguration(config.id, config.languageConfiguration);
  }
}

export function registerEditorExtensions() {
  // placeholder: no-op since modules/editor has been removed
}